<template>
    <div class="panel">
        <!-- 弹对话框 -->
       <el-dialog width="520px" :title="(action==='add'?'新增':'修改')+'分类'" :visible.sync="visible" @opened="opened">
            <el-form :model="form" :rules="rules" ref="form" label-width="100px">
                <el-form-item label="分类名称" prop="productcate">
                     <el-input v-model.trim="form.procate" ref="procate"></el-input>
                </el-form-item>
                <el-form-item label="上传图片:">
                    <el-upload
                        class="myavatar"
                        action="http://cloud.scnew.com.cn/api/user/upload"
                        :show-file-list="false"
                        :on-success="uploadSuccess"
                        :before-upload="beforeUpload">
                        <img v-if="form.picurl" :src="form.picurl">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="排序:">
                    <el-input-number v-model.number="form.orderid" type="number"/>
                </el-form-item>
                <el-form-item label="审核">
                    <el-switch v-model="form.state" :active-value="2" :inactive-value="1"></el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="visible=false">取消</el-button>
                <el-button type="primary" @click="save">确定</el-button>
            </div>
        </el-dialog>

        <!-- 头部 -->
        <div class="header">
            <h2>产品分类</h2>
            <div class="nav">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item to="/app">后台管理</el-breadcrumb-item>
                    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
                    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
        </div>
        <!-- 搜索 -->
        <div class="search">
            <div class="condition">
               <el-button v-if="ids.length" type="danger" size="small" @click="del(ids)">批量删除</el-button>
                <el-select v-model="condition.state" placeholder="是否审核"  size="small" clearable>
                    <el-option :value="2" label="审核"/>
                    <el-option :value="1" label="未审核"/>
                </el-select>
                <el-input v-model="condition.keyword" class="keyword" placeholder="请输入用户名/昵称/手机号" size="small" clearable/>
                <el-button  type="info" icon="el-icon-search" size="small" @click="search">搜索</el-button>
                <el-button type="danger" size="small" @click="add">新增</el-button>
            </div>
        </div>
        <!-- 表格 -->
        <el-table  v-loading='loading' :data="pageData" @selection-change="idChange">
            <el-table-column type="selection" width="80" prop="id"/>
            <el-table-column prop="orderid" label="排序" width="90"/>
            <el-table-column label="分类图片" width="300">
              <template v-slot="scope">
                  <img :src="scope.row.picurl" height="180">
              </template>
            </el-table-column>
            <el-table-column prop="procate" label="分类名称" width="150"/>
            <el-table-column label="审核">
              <template v-slot="scope">
                  <el-switch
                  v-model="scope.row.state"
                  :active-value="2"
                  :inactive-value="1"
                  @change="stateChange($event,scope.row.id)">
                  </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template v-slot="scope">
                  <el-button size="main" plain @click="edit(scope.row)">修改</el-button>
                  <el-button type="danger" size="smain" @click="del([scope.row.id])">删除</el-button>
                </template>
            </el-table-column>

        </el-table>
        <!-- 分页 -->
        <el-pagination
        background layout="total,prev,pager,next"
        :page-size="condition.pagesize"
        :current-page.sync="condition.page"
        :total="searchData.length"
        @current-change = "pageChange"
        class="mypage"
        />
    </div>
</template>
<script>

export default {
  data () {
    return {
      action: null,
      visible: false,
      form: {},
      rules: {
      },
      condition: { pagesize: 2, page: 1 },
      loading: true,
      tableData: [],
      ids: [],
      total: 0
    }
  },
  watch: {
    'condition.state' () {
      this.condition.page = 1
    },
    'condition.keyword' () {
      this.condition.page = 1
    }
  },
  computed: {
    searchData () {
      const { state, keyword } = this.condition
      return this.tableData.filter(item => {
        return (item.state === +state || !state) &&
          (item.procate.includes(keyword) || !keyword)
      }).sort((a, b) => a.orderid - b.orderid)
    },
    pageData () {
      const { page, pagesize } = this.condition
      const start = (page - 1) * pagesize
      const end = start + pagesize
      return this.searchData.slice(start, end)
    }
  },
  created () {
    this.query()
  },
  methods: {
    opened () {
      this.$refs.procate.focus()
    },
    query (refresh) {
      if (refresh) this.condition.page = 1
      // get()里放入后端接口，但是前端要和后端协议好接口的类型
      this.$http.get('productcate/list').then(res => {
        if (res.err > 0) {
          this.$message.error(res.desc)
        } else {
          this.tableData = res.result
          this.total = res.total
          setTimeout(_ => this.loading = false, 200)
        }
      })
    },
    // 搜索
    search () {
      this.query(true)

    },
    // 添加
    add () {
      this.action = 'add'
      this.form = {price:999,totla:99999}
      this.visible = true
    },
    // 修改
    edit (row) {
      this.action = 'edit'
      this.form = { ...row, password: '' }
      this.visible = true
    },

    // 弹出对话框确后添加
    save () {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.action === 'add') {
            this.$http.post('productcate/add', { ...this.form }).then(res => {
              if (res.err > 0) {
                this.$message.error(res.desc)
              } else {
                this.$message.success(res.desc)
                this.condition.page = 1
                this.query()
                this.visible = false
              }
            })
          } else if (this.action === 'edit') {
            this.$http.post('productcate/edit', { ...this.form }).then(res => {
              if (res.err > 0) {
                this.$message.error(res.desc)
              } else {
                this.$message.success(res.desc)
                this.query()
                this.visible = false
              }
            })
          }
        }
      })
    },
    // 删除
    del (ids) {
      this.$confirm('确定要删除吗', '提示').then(_ => {
        this.$http.post('productcate/del', { ids }).then(res => {
          if (res.err > 0) {
            this.$message.error(res.desc)
          } else {
            this.$message.success(res.desc)
            this.query()
          }
        })
      }).catch(() => {})
    },
    // 审核
    stateChange (state, id) {
      this.$http.post('productcate/state', { id, state }).then(res => {
        if (res.err > 0) {
          this.$message.error(res.desc)
        } else {
          this.$message.success(res.desc)
        }
      })
    },
    pageChange(page){
      this.query(false,{ page })
    },
    //上传图片
    beforeUpload (file) {
      const type = file.type.split('/')[1].toLowerCase()
      const isPic = ['jpeg', 'png', 'gif', 'jpg', 'webp']
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isPic.includes(type)) {
        this.$message.error('上传图片只能是 ' + isPic + ' 格式!')
      }

      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }

      return isPic && isLt2M
    },
    uploadSuccess (res) {
      if (res.err > 0) {
        this.$message.error(res.desc)
      } else {
        this.$message.success(res.desc)
        this.$set(this.form, 'picurl', res.result)
      }
    },
    idChange (row) {
      this.ids = row.map(item => item.id)
    }

  }
}
</script>
<style>
/* .header{
    display: inline-block;
}
.nav{
    position:absolute;
    right: 10px;
} */
</style>
<style lang="less">
.myavatar{
  .el-upload {
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    text-align: center;
    &:hover {
      border-color: #E60218;
    }
    img{
      display: block;
      width: 200px;
      height: 68px;
    }
    [class*="el-icon-"]{
      width: 200px;
      height: 68px;
      line-height: 68px;
      text-align: center;
      font-size: 24px;
      color: #8c939d;
    }
  }
}
</style>>
